package com.lilidp.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lilidp.dto.Result;
import com.lilidp.dto.UserDTO;
import com.lilidp.entity.Blog;
import com.lilidp.entity.User;
import com.lilidp.service.IBlogService;
import com.lilidp.service.IUserService;
import com.lilidp.utils.SystemConstants;
import com.lilidp.utils.UserHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 栗顺
 
 */
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Resource
    private IBlogService blogService;
    @Resource
    private IUserService userService;

    /**
     * 保存探店博文
     * @param blog
     * @return
     */
    @PostMapping
    public Result saveBlog(@RequestBody Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        blogService.save(blog);
        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 修改某个博文的点赞数量，每次+1
     * @param id
     * @return
     */
    @PutMapping("/like/{id}")
    public Result likeBlog(@PathVariable("id") Long id) {
        // 修改点赞数量
        blogService.update()
                .setSql("liked = liked + 1").eq("id", id).update();
        return Result.ok();
    }

    /**
     * 查询我的博文
     * @param current
     * @return
     */
    @GetMapping("/of/me")
    public Result queryMyBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        //获取登录用户
        UserDTO user = UserHolder.getUser();
        //分页查询出当前页中的博文
        Page<Blog> page = blogService.query().eq("user_id", user.getId()).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        //获取博文列表
        List<Blog> records=page.getRecords();
        //返回博文记录
        return Result.ok(records);
    }

    /**
     * 按照“最热”查询
     * @param current
     * @return
     */
    @GetMapping("/hot")
    public Result queryHotBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        //查询当前页的数据，按照点赞数降序
        Page<Blog> page = blogService.query().orderByDesc("liked").page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        //获取当前页的博客列表
        List<Blog> records=page.getRecords();
        //重置博客内容
        records.forEach(blog->{
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
        });
        //返回博客结果
        return Result.ok(records);

    }
}
